package old;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class GPXLoader {

	//TODO do a proper xml-parsing
	public static float[][] readFile(File gpxFile) throws IOException, ParseException {
		List<float[]> ret = new ArrayList<float[]>();
		BufferedReader r = new BufferedReader(new FileReader(gpxFile));
		String line = null;
		SimpleDateFormat sd = new SimpleDateFormat("hh:mm:ss");
		int timePoints = 0;
		long start = 0;
		double sum = 0;
		Calendar cal = Calendar.getInstance();
		while ((line = r.readLine()) != null) {
			if (line.startsWith("<trkpt")) {
				line = line.replace("", "");
				String c[] = line.split("><");
				String xy[] = c[0].split("\"");
				float lat = Float.parseFloat(xy[1]);
				float lon = Float.parseFloat(xy[3]);
				float ele = Float.parseFloat(c[1].replaceFirst("ele>", "").replace("</ele", ""));
				String ds = c[2].replaceFirst("time>", "").replace("</time", "").split("T")[1];
				long cT = sd.parse(ds).getTime();
				cT += 1000 * 60 * 60 * 4;//TODO make better 4h
				if (timePoints == 0) {
					start = cT;
				}
				float delta = (cT - start) / 1000;
				sum += delta;
				start = cT;
				//System.out.println(delta + " ]" + ds + "[ ad " + c[2] +  "       " + line);
				System.out.println(sum / 60 + " " + lat + " " + lon + " " + ele);
				ret.add(new float[]{(float) (sum / 60.0), lat, lon });
				timePoints++;
			}
		}
		System.err.println("Total time (min)" + sum / 60.0 + " number of timepoints " + timePoints);
		return ret.toArray(new float[ret.size()][]);
	}
	
	public static void main(String[] args) throws IOException, ParseException {
		File file = new File(("data/RK_gpx _2011-01-13_1222PM.gpx"));
//		float[][] res = readFile(file);
//		for (int i = 0; i < res.length - 1; i++) {
//			System.err.println(i + " " + Distance.haversine(res[i][1], res[i][2], res[i+1][1], res[i+1][2]));
//		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		System.err.println(sdf.parse("2011-01-13T12:22:58Z").getTime());
	}
	
}
